/**
 * Yolema.com Inc.
 * Copyright (c) 2011-2012 All Rights Reserved.
 */
package org.grayrabbit.pay.utils;

import java.text.SimpleDateFormat;
import java.util.Date;

import org.grayrabbit.pay.chinapay.config.ChinaPayConfigUtil;

/**
 * 生成订单ID编号
 * 
 * @author wy
 * @version $Id: GenerateTradeId.java, v 0.1 2012-6-6 上午9:15:15 wy Exp $
 */
public class GenerateTradeIdUtil {

    /**二级商户判断标示，前六位为808080*/
    private static final String TWO_LEVEL_MERCHANTS = "808080";

    /**
     * 根据数据库的主键生成银联的交易订单编号16位
     * <p>生成规则: 在订单前面补零
     * 
     * @param tradeId
     * @return
     */
    public static String generateChinaPayId(long tradeId) {
        String memId = ChinaPayConfigUtil.getChinaPayInfo().getMemId();
        StringBuilder sb = new StringBuilder();
        sb.append(tradeId);
        //先补全16位，首先肯定的前提是数据库的tradeId长度不会超过11位
        while (sb.length() <= 16) {
            sb.insert(0, 0);
        }
        if (memId.startsWith(TWO_LEVEL_MERCHANTS)) {
            //订单号从第5位到第9位必须和商户号的第11位到第15位相同
            sb.insert(sb.length() - 7, memId.substring(10, 15));
        }

        return sb.substring(sb.length() - 16);
    }

    /**
     * 交易订单号开头为1
     * 
     * @param tradeId
     * @return
     */
    public static String generateChinapnrId(long tradeId) {
        String orderId = getTradeId(tradeId);
        return "1" + orderId;
    }

    /**
     * 
     * @param tradeId
     * @return
     */
    private static String getTradeId(long tradeId) {
        Date date = new Date();
        String d = new SimpleDateFormat("yyyyMMdd").format(date);
        StringBuilder sb = new StringBuilder();
        sb.append(d);
        sb.append(tradeId);
        while (sb.length() <= 14) {
            sb.insert(0, 0);
        }
        //防止超过
        String orderId = sb.substring(0, 15);
        return orderId;
    }

    /**
     * 退款订单号开头为0
     * 
     * @param tradeId
     * @return
     */
    public static String generateChinapnrRefundId(long tradeId) {
        String orderId = getTradeId(tradeId);
        return "0" + orderId;
    }
}
